<template>
  <!-- <el-radio-group v-model="isCollapse" style="margin-bottom: 20px">
    <el-radio-button :value="false">expand</el-radio-button>
    <el-radio-button :value="true">collapse</el-radio-button>
  </el-radio-group> -->
  <el-menu
    default-active="2"
    class="el-menu-vertical-demo"
    :collapse="isCollapse"
    @open="handleOpen"
    @close="handleClose"
    @select="handleSelect"
  >
    <template v-for="(menu, i) in menuList">
      <el-sub-menu v-if="menu.children && menu.children.length" :index="menu.id" :key="menu.id">
        <template #title>
          <el-icon>
            <component :is="menu.icon"></component>
          </el-icon>
          <span>{{ menu.text }}</span>
        </template>
        <template v-for="(child, j) in menu">
          <el-sub-menu v-if="child.children && child.children.length" :index="child.id" :key="child.id">
            <template #title
              ><span>{{ child.text }}</span></template
            >
          </el-sub-menu>
          <el-menu-item v-else :index="child.id" :key="child.id">{{
            child.text
          }}</el-menu-item>
        </template>
      </el-sub-menu>
      <el-menu-item v-else :index="menu.id" :key="menu.id">        
        <el-icon>
            <component :is="menu.icon"></component>
        </el-icon>
        <template #title>{{ menu.text }}</template>
      </el-menu-item>
    </template>
  </el-menu>
</template>

<script lang="ts" setup>
import { ref, toRefs } from 'vue'
import { useRouter } from 'vue-router'
import {makeTree} from '@/common/util'

const router = useRouter()
// 从缓存中获取菜单数据，并转换为树结构

const menus_ = JSON.parse(localStorage.getItem('menus'))
const menus = ref(menus_) // 是响应式
const activeIndex = ref('')
const menuList = makeTree('id', 'parent', menus.value)
console.log('menuList',menuList)

const isCollapse = ref(true)
const handleOpen = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}
const handleClose = (key: string, keyPath: string[]) => {
  console.log(key, keyPath)
}
const handleSelect = (key: string, keyPath: string[]) => {
    console.log(key,keyPath)
  activeIndex.value = key
  getTargetUrl(key, keyPath, JSON.parse(JSON.stringify(menus.value)))

  
}
/*根据keyPath , menuList选出数据*/
const getTargetUrl = (key: string, keyPath: String[], menuList: any[]) => {
  if (keyPath.length > 0) {
    if (keyPath.length === 1) {
      menuList.forEach((item: any) => {
        if (item.id === key) {
          router.push(item.url)
          return false
        }
      })
    } else {
      let list: any[];
      menuList.forEach((item: any) => {
        if (item.id === keyPath[0]) {
          list = item.children
        }
      })
      getTargetUrl(key, keyPath.slice(1), list);
    }
  }
}


</script>

<style>
.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  min-height: 400px;
}
.el-menu {
  border:none !important
}
</style>
